//
//  KDDetailSubscribController.m
//  WangJingApp
//
//  Created by 魏强 on 17/1/6.
//  Copyright © 2017年 KDTech. All rights reserved.
//

#import "KDDetailSubscribController.h"
#import "KDComment.h"
#import "KDCommentCell.h"
#import "Masonry.h"
#import "KDSubCommentFooterView.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "KDSubscripRequestTool.h"
#import "KDGetCommentListParam.h"
#import "KDGetCommentListResult.h"
#import "KDAddCommentParam.h"
#import "SVProgressHUD.h"
#import "UIViewController+BackButtonHandler.h"
#import "WQSeparatorView.h"
#import "KDSingleWebController.h"
#import "KDCollectRequestTool.h"
#import "KDFavorTypeListResult.h"
#import "AlertTableView.h"
#import "KDReportController.h"
#import "IFMShareView.h"
#import "NSString+KD.h"
static CGFloat const FOOTERBAR_H = 44;
static CGFloat const MAGIN = 30;

@interface KDDetailSubscribController ()<UITableViewDelegate,UITableViewDataSource, UITextViewDelegate, UIWebViewDelegate, BackButtonHandlerProtocol,KDReportControllerDelegate>
/**  底部scrollView */
@property (nonatomic, weak) UIScrollView *scrollView;

/**  scrollView底部的container */
@property (nonatomic, weak) UIView *container;

/**  webView */
@property (nonatomic, weak) UIWebView *webview;
//webView需要的url
@property (nonatomic, copy) NSString * webViewUrl;
/** *  当前网页的url */
@property (nonatomic, copy) NSString * currentUrl;
/**  底部工具条 */
@property (nonatomic, strong) KDSubCommentFooterView *footerBar;
/**  评论版 */
@property (nonatomic, weak) UITableView *commentTableView;
/**  所有的comment数据 */
@property (nonatomic, strong) NSArray *comments;
/**  footer高度约束 */
@property (nonatomic, strong) MASConstraint *footerCons_h;
/** 正文浏览后的偏移量y */
@property (nonatomic, assign) CGFloat contentOffestY;
/**  段头 */
@property (nonatomic, strong) UIView *header;
/**  <#Description#> */
@property (nonatomic, weak) UILabel *titleLb;

/**  <#Description#> */
@property (nonatomic, weak) UIButton *goOriginBtn;
/**  需要分享的类型 */
@property(nonatomic, strong) NSMutableArray *shareArray;
@end

@implementation KDDetailSubscribController
#pragma mark - 懒加载区
- (NSArray *)comments
{
    if (!_comments) {
        _comments = [NSArray new] ;
    }
    return _comments;
}
- (NSMutableArray *)shareArray{
    if (!_shareArray) {
        _shareArray = [NSMutableArray array];
        
        [_shareArray addObject:IFMPlatformNameSms];
        [_shareArray addObject:IFMPlatformNameSina];
        [_shareArray addObject:IFMPlatformNameWechat];
//        [_shareArray addObject:IFMPlatformNameQQ];
//        [_shareArray addObject:IFMPlatformNameAlipay];
    }
    return _shareArray;
}
- (void)setID:(NSInteger)ID{
    _ID = ID;
    //在这里获取model
}
#pragma mark - 生命周期区
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BackGroundColor;
//    self.webViewUrl = self.model.viewUrl;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupScrollView];
    [self setupHeaderView];
    [self setupTitleView];
    [self creatWebView];
    [self setupUnderView];
//    [self setupCommentTableView];
    [self setupOtherView];
    [self setupFootBar];
    [self loadData];
    [self loadComment];
    

}
#pragma mark - 板块布置区
- (void)setupScrollView{
    //初始化underScrollView
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.delegate = self;
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    UIView *container = [UIView new];
    container.backgroundColor = [UIColor clearColor];
    self.container = container;
    [scrollView addSubview:container];
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(scrollView);
        make.width.equalTo(scrollView);
//        make.height.mas_equalTo(screenH -64);
    }];
    self.scrollView = scrollView;
//    scrollView.backgroundColor = RandomColor;
    
    //    underScrollView.contentSize = CGSizeMake(BTN_WIDTH * PAGE_NUMBER, HEADSCROLLH);
    scrollView.backgroundColor = [UIColor whiteColor];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
   

}

- (void)setupHeaderView{
    UIView *header = [[UIView alloc]init];
    self.header = header;
    header.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:header];
    
    [header mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.container);
        make.left.equalTo(self.container);
        make.right.equalTo(self.container);
        make.height.mas_equalTo(60);
    }];
    
    //时间
    UIButton *timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [header addSubview:timeBtn];
    [timeBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -8, 0, 0)];
    [timeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.container).offset(MAGIN);
        make.top.equalTo(self.container).offset(5);
        make.height.mas_equalTo(25);
    }];
    
    [timeBtn setImage:[UIImage imageNamed:@"time"] forState:UIControlStateNormal];
    [timeBtn setTitle:self.model.craw_publishtime forState:UIControlStateNormal];
    timeBtn.backgroundColor = [UIColor clearColor];
    [timeBtn setTitleColor:WQColor(153, 153, 153) forState:UIControlStateNormal];
    timeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    //来源
    UIButton *typeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [header addSubview:typeBtn];
    [typeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(timeBtn);
        make.top.mas_equalTo(timeBtn.mas_bottom);
        make.height.mas_equalTo(25);
    }];
    UIImage *image ;
    NSString *siteName ;
    switch (self.model.site_type) {
        case 1:
        {
            siteName = @"新闻";
            image = [UIImage imageNamed:@"news"];
            break;
        }
        case 2:
        {
            siteName = @"视频";
            image = [UIImage imageNamed:@"video"];
            break;
        }
        case 3:
        {
            siteName = @"论坛";
            image = [UIImage imageNamed:@"bbs"];
            break;
        }
        case 4:
        {
            siteName = @"问答/知道";
            image = [UIImage imageNamed:@"news"];
            break;
        }
        case 5:
        {
            siteName = @"平媒";
            image = [UIImage imageNamed:@"news"];
            break;
        }
        case 6:
        {
            siteName = @"博客";
            image = [UIImage imageNamed:@"blog"];
            break;
        }
        case 7:
        {
            siteName = @"境外";
            image = [UIImage imageNamed:@"vpn"];
            break;
        }
        case 8:
        {
            siteName = @"维语";
            image = [UIImage imageNamed:@"minority"];
            break;
        }
        case 9:
        {
            siteName = @"藏语";
            image = [UIImage imageNamed:@"minority"];
            break;
        }
        case 10:
        {
            siteName = @"微博";
            image = [UIImage imageNamed:@"weibo"];
            break;
        }
        case 11:
        {
            siteName = @"微信";
            image = [UIImage imageNamed:@"wechat"];
            break;
        }
        default:
            break;
    }
    [typeBtn setImage:image forState:UIControlStateNormal];
    [typeBtn setTitle:siteName forState:UIControlStateNormal];
    [typeBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -8, 0, 0)];
    typeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    typeBtn.backgroundColor = [UIColor clearColor];
    [typeBtn setTitleColor:WQColor(153, 153, 153) forState:UIControlStateNormal];
    
    //正反面属性
    UIImageView *posnegIv = [[UIImageView  alloc]init];
    [header addSubview:posnegIv];
    
    switch (self.model.analy_posneg) {
        case 1:
            image = [UIImage imageNamed:@"feature_positive"];
            break;
        case 0:
            image = [UIImage imageNamed:@"feature_neutral"];
            break;
        case -1:
            image = [UIImage imageNamed:@"feature_sad"];
            break;
        default:
            break;
    }
    posnegIv.image = image;
    
    [posnegIv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(header.mas_right).offset(-MAGIN);
        make.centerY.mas_equalTo(header.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    //line
    UIView *line = [[UIView alloc]init];
    [header addSubview:line];
    line.backgroundColor = WQColor(244, 246, 246);
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(header);
        make.right.equalTo(header);
        make.bottom.equalTo(header);
        make.height.equalTo(@1);
    }];
    
    
    
}

- (void)setupTitleView{
    //标题
    UILabel *titleLb = [[UILabel alloc]init];
    self.titleLb = titleLb;
    [self.scrollView addSubview:titleLb];
    titleLb.attributedText = [NSString praseHtmlStr:self.model.craw_title];
    titleLb.textColor = [UIColor blackColor];
//    titleLb.textAlignment = NSTextAlignmentCenter;
    titleLb.font = [UIFont systemFontOfSize:18 weight:0.7];
    titleLb.numberOfLines = 0;
    [titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.container).offset(MAGIN);
        make.right.mas_equalTo(self.container).offset(-MAGIN);
        make.top.mas_equalTo(self.header.mas_bottom).offset(20);
    }];
}

- (void)creatWebView{
    UIWebView *webView = [[UIWebView alloc]init];
    [self.scrollView addSubview:webView];
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titleLb.mas_bottom).offset(5);
        make.left.mas_equalTo(self.container).offset(MAGIN);
        make.right.mas_equalTo(self.container).offset(-MAGIN);
        make.height.mas_equalTo(screenH *0.5);
    }];
    //去除webView底部黑线
    webView.backgroundColor = [UIColor clearColor];
    webView.opaque = NO;
    webView.scrollView.scrollEnabled = NO;
    webView.delegate = self;
    webView.scalesPageToFit = YES;
//    [webView sizeToFit];
    self.webview = webView;
    
   
}
- (void)setupUnderView{
    UIView *underView = [[UIView alloc]init];
    underView.backgroundColor = WQColor(247, 249, 250);
    [self.scrollView addSubview:underView];
    [underView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.container);
        make.top.mas_equalTo(self.webview.mas_bottom);
        make.bottom.mas_equalTo(self.container).offset(FOOTERBAR_H);
    }];
    
}
//#warning 使用mas_equalTo的时候，如果对象是别人的位置，一定也要加上mas_前缀！！！
- (void)setupCommentTableView{
//    UIView *
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.scrollView addSubview:tableView];
    self.commentTableView = tableView;

    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.webview.mas_bottom).offset(10);
        make.left.mas_equalTo(self.container.mas_left).offset(10);
        make.right.mas_equalTo(self.container.mas_right).offset(-10);
        make.height.mas_equalTo(0);
//        make.bottom.mas_equalTo(self.container.mas_bottom).offset(-FOOTERBAR_H);

    }];
    self.commentTableView.layer.cornerRadius = 5;
    self.commentTableView.layer.borderWidth = 1;
    self.commentTableView.layer.borderColor = WQColor(244, 244, 244).CGColor;
    self.commentTableView.clipsToBounds = YES;
    tableView.autoresizingMask &= ~UIViewAutoresizingFlexibleBottomMargin;
    tableView.estimatedRowHeight = 44.0;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    
    UINib *xib =[UINib nibWithNibName:@"KDCommentCell" bundle:nil] ;
    [tableView registerNib:xib forCellReuseIdentifier:@"KDCommentCell"];
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadComment)];
    [tableView addObserver:self forKeyPath:@"contentSize" options:0 context:nil];
}
/**
 *  创建 底部的复制链接和查看原文等辅助View
 */
- (void)setupOtherView{
    UILabel *noticeLb = [[UILabel alloc]init];
    noticeLb.text = @"原文由晴朗舆情转码以便移动阅读";
    noticeLb.font = [UIFont systemFontOfSize:12 weight:0.5];
    noticeLb.textColor = WQColor(139, 139, 139);
    noticeLb.backgroundColor = [UIColor clearColor];
    noticeLb.textAlignment = NSTextAlignmentCenter;
    [self.scrollView addSubview:noticeLb];
    
    [noticeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(15);
        make.top.mas_equalTo(self.webview.mas_bottom).offset(20);
        make.centerX.equalTo(self.container);
        
    }];
    UIButton *copyLinkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [copyLinkBtn setTitle:@"复制链接" forState:UIControlStateNormal];
    [copyLinkBtn addTarget:self action:@selector(copyLinkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    copyLinkBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    copyLinkBtn.backgroundColor = [UIColor whiteColor];
    copyLinkBtn.layer.cornerRadius = 10 ;
    copyLinkBtn.clipsToBounds = YES;
    copyLinkBtn.layer.borderColor = WQColor(231, 231, 231).CGColor;
    copyLinkBtn.layer.borderWidth = 1;
    [copyLinkBtn setTitleColor:WQColor(176, 176, 176) forState:UIControlStateNormal];;
    [self.scrollView addSubview:copyLinkBtn];
    
    [copyLinkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(90);
        make.height.mas_equalTo(26);
//        make.size.mas_equalTo(CGSizeMake(75, 20));
        make.top.mas_equalTo(noticeLb.mas_bottom).offset(5);
        make.centerX.equalTo(self.container).offset(-70);
//        make.bottom.mas_equalTo(self.container.mas_bottom).offset(-FOOTERBAR_H - 10);

    }];
    
    UIButton *goOriginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.goOriginBtn = goOriginBtn;
    [goOriginBtn setTitle:@"查看原文" forState:UIControlStateNormal];
    [goOriginBtn addTarget:self action:@selector(goOriginBtnBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    goOriginBtn.backgroundColor = [UIColor whiteColor];
     goOriginBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    goOriginBtn.layer.cornerRadius = 10 ;
    goOriginBtn.clipsToBounds = YES;
    goOriginBtn.layer.borderColor = WQColor(231, 231, 231).CGColor;
    goOriginBtn.layer.borderWidth = 1;
    [goOriginBtn setTitleColor:WQColor(176, 176, 176) forState:UIControlStateNormal];;
    [self.scrollView addSubview:goOriginBtn];
    
    [goOriginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(90);
        make.height.mas_equalTo(26);
        make.top.mas_equalTo(noticeLb.mas_bottom).offset(5);
        make.centerX.equalTo(self.container).offset(70);
        make.bottom.mas_equalTo(self.container.mas_bottom).offset(-FOOTERBAR_H - 10);

    }];
    

}

/**
 *  创建底部工具栏
 */
- (void)setupFootBar{
    KDSubCommentFooterView * footBar = [KDSubCommentFooterView inputView];
    footBar.backgroundColor = BackGroundColor;
    self.footerBar = footBar;
    self.footerBar.commentTv.delegate = self;
    self.footerBar.commentTv.placeholder = @"请输入批示内容";
    [self.view addSubview:self.footerBar];
    
    self.footerBar.collectBtn.selected = self.model.isCollection;
    [self.footerBar.collectBtn addTarget:self action:@selector(collectBtnClick:)];
    [self.footerBar.commentBtn addTarget:self action:@selector(reportBtnClick:)];
    [self.footerBar.shareBtn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.footerCons_h = [[footBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(FOOTERBAR_H);
//        make.top.mas_equalTo(self.goOriginBtn.mas_bottom).offset(20);

       make.width.mas_equalTo(screenW);
//        make.size.mas_equalTo(CGSizeMake(screenW, FOOTERBAR_H));
        make.bottom.mas_equalTo(self.view.mas_bottom);
        make.left.mas_equalTo(self.view.mas_left);
    }] firstObject];
    
}
#pragma mark - 事件点击区
- (void)collectBtnClick:(UIButton *)collectBtn{
    WS(ws);
    KDFavorParam *param = [[KDFavorParam alloc]init];
    if (self.footerBar.collectBtn.selected) {//已经选中的，就取消
        param.info_id = [NSString stringWithFormat:@"%ld",self.model.ID];
        
        [KDCollectRequestTool cancelFavorMsgWithParam:param success:^(KDBaseResult *responseObejct) {
            if ([responseObejct.code isEqualToString:@"1"]) {
                [SVProgressHUD showSuccessWithStatus:@"取消收藏成功" maskType:SVProgressHUDMaskTypeGradient];
                ws.footerBar.collectBtn.selected = NO;
                ws.model.isCollection = NO;
                
            }else{
                [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            }
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        }];
    }else{
        [self addFavar];
    }
//    [self loadFavarWithCurrentStatus:self.footerBar.collectBtn.selected];
    
}

/**
 *  添加收藏的一系列操作
 *
 *  @param cell
 */
- (void)addFavar{
    __weak __typeof(self)weakSelf = self;
    //1.弹出收藏夹列表（需要一个拉取收藏夹列表请求）
    KDBaseParam *param = [[KDBaseParam alloc]init];
//    param.method = @"collection/type/myCollectionType";
    [KDCollectRequestTool getFavorTypeListWithParam:param success:^(KDFavorTypeListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            AlertTableView *modelView = [[AlertTableView alloc] init];
            __weak typeof(AlertTableView) *weakModelView =modelView;
            
            modelView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            modelView.modalTransitionStyle =  UIModalTransitionStyleCrossDissolve;
            modelView.AlertFromDirect = fromDirectCenter;
            modelView.titleString = @"收藏夹列表";
            modelView.rowHight = 45;
            modelView.viewState = viewStateGray;
            modelView.AlertArray = responseObejct.data;
            
            modelView.doneBtnClickWithType = ^(KDFavorType *selectTyle){
                //2.选中一个收藏夹，返回被选中的文件夹的model！
                KDFavorParam *param = [[KDFavorParam alloc]init];
                param.info_id = [NSString stringWithFormat:@"%ld",weakSelf.model.ID];
                param.post_time = weakSelf.model.craw_publishtime;
                param.type_id = [NSString stringWithFormat:@"%ld", selectTyle.type_id];
                param.url = weakSelf.model.craw_url;
                param.website_name = weakSelf.model.site_name;
                param.author = weakSelf.model.craw_author;
                param.emotionType = [NSString stringWithFormat:@"%ld", weakSelf.model.analy_posneg];
                param.title = weakSelf.model.craw_title;

                //3.添加收藏！
                [KDCollectRequestTool addFavorMsgWithParam:param success:^(KDBaseResult *result) {
                    if ([result.code isEqualToString:@"1"]) {
                        [SVProgressHUD showSuccessWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
                        weakSelf.footerBar.collectBtn.selected = YES;
                        weakSelf.model.isCollection = YES;
                        
                        [weakModelView dismissSelfView];
                    }else{
                        [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
                    }
                } failure:^(NSError *error) {
                    [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
                }];
            };
            
            [weakSelf presentViewController:modelView animated:YES completion:nil];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
    }];
}

- (void)reportBtnClick:(UIButton *)btn{
    KDReportController *reportCtrl = [[KDReportController alloc]init];
    KDSubscribCellModel *model = self.model;
    KDPatrolgetReportParam *param = [[KDPatrolgetReportParam alloc]init];
    param.url = model.craw_url;
    param.info_title = model.craw_title;
    param.info_content = model.craw_content;
    param.website_type = model.site_type;
    param.website_name = model.site_name;
    reportCtrl.param = param;
//    reportCtrl.type = 1;
    reportCtrl.delegate = self;
    [self.navigationController pushViewController:reportCtrl animated:YES];
    
//    CGFloat h = self.webview.height;
//
//    if (self.scrollView.contentOffset.y < h  ) {
//        self.contentOffestY = self.scrollView.contentOffset.y;
//    }
//    BOOL selected = self.footerBar.commentBtn.selected;
//    self.footerBar.commentBtn.selected = !selected;
////    [self.footerBar.commentTv becomeFirstResponder];
//    if (self.footerBar.commentBtn.selected) {//选中了，就直接去评论区
//        [self.scrollView setContentOffset:CGPointMake(0, h) animated:YES];
//    }else{//没选中，就过滤掉评论区的offest，回到原来征文的offest
//        
//        [self.scrollView setContentOffset:CGPointMake(0, self.contentOffestY) animated:YES];
//
//    }

    //1.跳转到评论区域
}

- (void)shareBtnClick:(WQVerticalBtn *)btn{
    IFMShareView *shareView = [[IFMShareView alloc] initWithItems:self.shareArray itemSize:CGSizeMake(80,120) DisplayLine:YES];
    shareView = [self addShareContent:shareView];
    shareView.itemSpace = 10;
    [shareView showFromControlle:self];
}
//添加分享的内容
- (IFMShareView *)addShareContent:(IFMShareView *)shareView{
    [shareView addText:@"科盾科技"];
    [shareView addURL:[NSURL URLWithString:self.model.craw_url]];
    [shareView addImage:[UIImage imageNamed:@"AppIcon"]];
    
    return shareView;
}
/**
 *  复制链接按钮被点击了
 */
- (void)copyLinkBtnClick:(UIButton *)btn{
    UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
    [pasteboard setString:self.model.craw_url];
    [SVProgressHUD showSuccessWithStatus:@"复制成功" maskType:SVProgressHUDMaskTypeGradient];

}

- (void)goOriginBtnBtnClick:(UIButton *)btn{
    KDSingleWebController *web = [[KDSingleWebController alloc]init];
    web.webUrl = self.model.craw_url;
    [self.navigationController pushViewController:web animated:YES];
}

#pragma mark - 网络请求区
- (void)loadData{
//    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:_webViewUrl]];

    [self.webview loadHTMLString:self.model.craw_content baseURL:nil];
    
}
- (void)sendMsgWithText:(NSString *)text{
    KDAddCommentParam *param = [[KDAddCommentParam alloc]init];
//    param.msgNo = self.model.msg_no;
    param.content = text;
    param.method = @"rss/comment";
    [KDSubscripRequestTool addCommentWithParam:param success:^(KDBaseResult *responseObejct) {
        
        if ([responseObejct.status isEqualToString:@"1"]) {
            [self loadComment];
//            self.model.isOpinion = YES;
        }
    } failure:^(NSError *error) {
        KDLog(@"%@",error);
    }];
}
- (void)loadComment{
//    KDGetCommentListParam *param = [[KDGetCommentListParam alloc]init];
//    param.method = @"rss/comment/list";
////    param.msgNo = self.model.msg_no;
//    [KDSubscripRequestTool getCommentListWithparam:param success:^(KDGetCommentListResult *responseObejct) {
//        if ([responseObejct.status isEqualToString:@"1"]) {
//            self.comments = responseObejct.data;
//            [self.commentTableView reloadData];
//            [self.commentTableView.header endRefreshing];
//        }
//    } failure:^(NSError *error) {
//        KDLog(@"%@", error);
//    }];
    
}
/**
 *  发送收藏或取消收藏的请求
 *
 *  @param collect 点击之前的状态是已收藏还是未收藏
 */
//- (void)loadFavarWithCurrentStatus:(BOOL)collect{
//    
//}
- (NSArray *)getFakeData
{
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"FakeSubComment" ofType:@"plist"];
    return [KDComment objectArrayWithFile:plistPath];
    
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.comments.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDCommentCell *cell = [KDCommentCell cellWithTableView:tableView];
    //    KDLog(@"waimian%d", indexPath.row);
    if (tableView == self.commentTableView)
    {
        if (self.comments.count != 0)
        {
            cell.model = self.comments[indexPath.row];
        }
        return cell;
    }else{
        return cell;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //    if (!self.header) {
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenW, 44)];
    header.backgroundColor = [UIColor whiteColor];
    self.header = header;
    UILabel * lb1 = [self createLabelWithTitle:@"共" frame:CGRectMake(10, 0, 0, self.header.height)];
    UIButton *comentNumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //        KDLog(@"self.infoArr.count:%ld", self.infoArr.count);
    NSString *num = [NSString stringWithFormat:@"%ld", self.comments.count];
    [comentNumBtn setTitle:num forState:UIControlStateNormal];
    comentNumBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    CGSize titleSize = [num sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:comentNumBtn.titleLabel.font.fontName size:13]}];
    comentNumBtn.frame = CGRectMake(CGRectGetMaxX(lb1.frame), 0, titleSize.width+5, 15);
    
    
//    [comentNumBtn addTarget:self action:@selector(comentNumBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    comentNumBtn.backgroundColor = [UIColor redColor];
    comentNumBtn.layer.cornerRadius = 5;
    comentNumBtn.clipsToBounds = YES;
    [comentNumBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];;
    [self.header addSubview:comentNumBtn];
    comentNumBtn.centerY = header.centerY;
    
    [self createLabelWithTitle:@"条回复" frame:CGRectMake(CGRectGetMaxX(comentNumBtn.frame), 0, 0, self.header.height)];
    //    }
    
    return self.header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}
- (UILabel *)createLabelWithTitle:(NSString *)title frame:(CGRect)frame{
    UILabel *labelName = [[UILabel alloc]init];
    labelName.frame = frame;
    labelName.text = title;
    [labelName sizeToFit];
    labelName.centerY = self.header.centerY;
    [self.header addSubview:labelName];
    return labelName;
}
#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView{
    KDLog(@"%s", __func__);
}
- (void)textViewDidChange:(UITextView *)textView{
    //获取ContentSize
    CGFloat contentH = textView.contentSize.height;
    KDLog(@"%f", contentH);
    // 大于33，超过一行的高度/ 小于68 高度是在三行内
    if (contentH < 68 ) {
        
        [self.footerBar mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(contentH +18);
        }];
    }
    NSString *text = textView.text;


    // 换行就等于点击了的send
    if ([text rangeOfString:@"\n"].length != 0) {
//        KDLog(@"发送数据 %@",text);
        
        // 去除换行字符
        text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        [self sendMsgWithText:text];
        //清空数据
        textView.text = nil;
        
        // 发送完消息 把inputView的高度改回来
        [self.footerBar mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(FOOTERBAR_H);
        }];
        
    }else{
        KDLog(@"%@",textView.text);
        
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"KDCommentCell" configuration:^(KDCommentCell * cell) {
            cell.model = self.comments[indexPath.row];
    }];
}
#pragma mark - 通知接收区

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    //将UITableview的高度设置为内容的大小
    
//    KDLog(@"高度变了");
    [self.commentTableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.commentTableView.contentSize.height);
    }];
    
}


- (void)dealloc{
    [self.commentTableView removeObserver:self forKeyPath:@"contentSize" context:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self];


}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '50%'";
    
//    [webView stringByEvaluatingJavaScriptFromString:str];
    //方法1
//    CGFloat documentHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
//
//    NSLog(@"documentSize = {%f, %f}", documentHeight, documentHeight);
    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '300%'";
    [self.webview stringByEvaluatingJavaScriptFromString:str];
    
    CGFloat documentHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue]/3;
    //方法2.
//    CGFloat documentHeight = webView.scrollView.contentSize.height;
    [webView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(documentHeight);
    }];

}
#pragma mark - BackButtonHandlerProtocol
-(BOOL)navigationShouldPopOnBackButton{
    if (_delegate && [_delegate respondsToSelector:@selector(backFromDetailSubscribCtrWithModel:)]) {
        [_delegate backFromDetailSubscribCtrWithModel:self.model];
    }
    return YES;
}

#pragma mark - KDReportControllerDelegate
- (void)reportCtrlPopBySuccessReportWithIndex:(NSInteger)index{
    
}
@end
